package UDP;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket();
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("请输出需要发送的消息:");
            String msg = scanner.nextLine();
            if ("exit".equals(msg)){
                System.out.println("成功退出!!!");
                //最后记得要关闭
                socket.close();
                break;
            }
            //将字符串转化为字节数组
            byte[] m = msg.getBytes();
            //假如：发送的地方正是本机，就可以通过 InetAddress.getLocalHost() 方法来获取到 IP 地址对象，
            //发送的程序端口号假设为: 9090
            DatagramPacket packet = new DatagramPacket(m,m.length, InetAddress.getLocalHost(),9090);
            //接着就可以发送消息了
            socket.send(packet);

            //接收消息
            byte[] receiveMsg = new byte[1024*1024];
            DatagramPacket receivePacket = new DatagramPacket(receiveMsg, receiveMsg.length);
            socket.receive(receivePacket);
            //输出消息

            String ret = new String(receiveMsg,0,receivePacket.getLength());
            System.out.println(ret);
        }
    }
}


